// pages/shop/shop.js
import {
  request
} from "../../request/index.js";
import {
  showModal,
  showToast
} from "../../utils/asyncWx.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  // 设置购物车状态同时重新计算底部工具栏的数据 全选 总价格 购买的数量

  async handleOrderPay() {
    const token = wx.getStorageSync("token")

    if (!token) {
      wx.navigateTo({
        url: '/pages/auth/index',
      })
      return
    }
    console.log('已经存在token');
    // const header = {
    //   Authorization: token
    // }
    const order_price = this.data.totalPrice
    const consignee_addr = this.data.address.all
    const cart = this.data.cart

    let goods = []
    cart.forEach(v => goods.push({
      goods_id: v.goods_id,
      goods_number: v.num,
      goods_price: v.goods_price
    }))
    const orderPramas = {
      order_price,
      consignee_addr,
      goods
    }
    let ces = await request({
      url: '/my/orders/create',
      data: orderPramas,
      method: 'POST'
    })
    const order_number = ces.data.message.order_number
    console.log(order_number);
    let res = await request({
      url: '/my/orders/chkOrder',
      data: order_number,
      method: 'POST'
    })
    console.log(res);

  },
  onShow() {
    const address = wx.getStorageSync("address")
    let cart = wx.getStorageSync("cart") || []
    cart = cart.filter(v => v.checked)
    this.setData({
      address
    })
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price
      totalNum += v.num;
    })
    this.setData({
      cart,
      totalPrice,
      totalNum,
      address
    })
    // // const allChecked = cart.length ? cart.every(v => v.checked) : false
    // let allChecked = true
    // let totalPrice = 0;
    // let totalNum = 0;
    // cart.forEach(v => {
    //   if (v.checked) {
    //     totalPrice += v.num * v.goods_price
    //     totalNum += v.num;
    //   } else {
    //     allChecked = false
    //   }
    // })
    // allChecked = cart.length != 0 ? allChecked : false
    // this.setData({
    //   address,
    //   cart,
    //   allChecked,
    //   totalPrice,
    //   totalNum
    // })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  // onShow: function () {

  // },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})